import 'dart:convert';
import 'dart:io';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:github_client_app/common/global.dart';
import 'package:github_client_app/models/index.dart';

class Git {
  BuildContext context;
  Options _options;

  Git([this.context]) {
    _options = Options(extra: {"context": context});
  }

  static Dio dio = Dio(BaseOptions(
    baseUrl: 'https://api.github.com/',
    headers: {
      HttpHeaders.acceptHeader: "application/vnd.github.squirrel-girl-preview,"
          "application/vnd.github.symmetra-preview+json",
    },
  ));

  static void init() {
    dio.interceptors.add(Global.netCache);
    dio.options.headers[HttpHeaders.authorizationHeader] = Global.profile.token;

    if (!Global.isRelease) {
//      (dio.httpClientAdapter as DefaultHttpClientAdapter).onHttpClientCreate =
//          (client) {
//        client.findProxy = (uri) {
//          return 'PROXY ';
//        };
//        client.badCertificateCallback =
//            (X509Certificate cert, String host, int port) => true;
//      };
    }
  }

  Future<User> login(String username, String pwd) async {
    String basic = 'Basic ' + base64.encode(utf8.encode('$username:$pwd'));
    var response = await dio.get(
      'users/$username',
      options: _options.merge(
        headers: {HttpHeaders.authorizationHeader: basic},
        extra: {'noCache': true},
      ),
    );
    dio.options.headers[HttpHeaders.authorizationHeader] = basic;
    Global.netCache.cache.clear();
    Global.profile.token = basic;
    return User.fromJson(response.data);
  }

  Future<List<Repo>> getRepos(
      {Map<String, dynamic> queryParameters, refresh = false}) async {
    if (refresh) {
      _options.extra.addAll({'refresh': true, 'list': true});
    }
    var response = await dio.get<List>(
      'user/repos',
      queryParameters: queryParameters,
      options: _options,
    );
    return response.data.map((e) => Repo.fromJson(e)).toList();
  }
}
